import { login, getUserInfo, userLogOut } from '../../api/user'
import { setToken, getToken, setBtnPermission } from '../../libs/util'

export default {
  state: {
    severUserInfo: {},
    token: getToken()
  },
  getters: {
    userInfo: state => state.severUserInfo
  },
  mutations: {
    setSeverUserInfo (state, severUserInfo) {
      state.severUserInfo = severUserInfo
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    handleLogin ({ commit }, { userName, password, url, code }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password,
          url,
          code
        }).then(res => {
          setBtnPermission('')
          const data = res.data
          // 可能是验证码错误
          if (data.errcode === 9999) {
            resolve(data)
          }
          if (data.data.errcode === 0 || data.errcode === 1001) {
            commit('setToken', data.data.key)
          }
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    handQrcodeLogin ({ commit }, { token }) {
      return new Promise((resolve, reject) => {
        setBtnPermission('')
        commit('setToken', token)
        resolve({})
      })
    },
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        userLogOut().then(() => {
          commit('setToken', '')
          setBtnPermission('')
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // resolve()
      })
    },
    getUserInfo ({ state, commit }, $router) {
      return new Promise((resolve, reject) => {
        try {
          // 本地调试注释
          getUserInfo(state.token).then(res => {
            const data = res.data
            if (data.errcode === 10001) {
              $router.push({ path: '/login' })
            }
            commit('setSeverUserInfo', data)
            // 放入localstorage以解决在新tab页再次打开系统时，vuex信息丢失的问题
            localStorage.setItem('severUserInfo', JSON.stringify(data.data))
            resolve(data)
            // resolve({})
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    setUserInfo ({ commit, rootState }, data) {
      commit('setSeverUserInfo', data)
    }
  }
}
